package demo.android.myapplication.demos.animation

import android.animation.ObjectAnimator
import android.animation.TypeEvaluator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.view.View
import androidx.core.graphics.minus
import cn.android.basic.dp

/**
 * <br>createBy Gw
 * <br>createTime: 2021/7/9 17:18
 */
class PointView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        strokeWidth = 10.dp
        strokeCap = Paint.Cap.ROUND
    }
    var point = PointF(10.dp, 10.dp)
        set(value) {
            field = value
            invalidate()
        }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        val animator =
            ObjectAnimator.ofObject(this, "point", PointTypeEvaluator(), PointF(100.dp, 200.dp))
        animator.startDelay = 1000
        animator.start()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawPoint(point.x, point.y, paint)
    }
}

class PointTypeEvaluator : TypeEvaluator<PointF> {

    override fun evaluate(fraction: Float, startValue: PointF, endValue: PointF): PointF {
        val diff = endValue - startValue
        diff.run {
            set(x * fraction + startValue.x, y * fraction + startValue.y)
        }
        return diff
    }

}